#!/usr/bin/python
import sqlite3
import os
import cgi
import cgitb
from Cookie import SimpleCookie
from pygallib import userlib
from pygallib import usersession
from pygallib import layoutlib
from pygallib import albumlib
from pygallib import picturelib

cgitb.enable()

logged_in = usersession.logged_in()
fields = cgi.FieldStorage()
conn = None
album = None

if "id" in fields:
  bad_input = False
  try:
    album_id = int(fields["id"].value)
  except ValueError:
    bad_input = True 
  if not bad_input:
    # Album before we make any changes to it
    album = albumlib.get_album(album_id)
    # Get user who created album
    user = userlib.get_user_by_id(album["user_id"])
    user_authorized = False
    if logged_in:
      session_user = usersession.get_session_user()
      if (session_user["user_id"] == user["user_id"] or 
          session_user["root"] == 1):
        user_authorized = True
    # Execute any user requested commands
    if user_authorized:
      if "cmd" in fields:
        if "delete" == fields["cmd"].value:
          picturelib.remove_picture(album_id, user["username"], 
              fields["picid"].value)
        if "mkpublic" == fields["cmd"].value:
          albumlib.change_visibility(album_id, 1)
        if "mkprivate" == fields["cmd"].value:
          albumlib.change_visibility(album_id, 0)
    # Get album information
    album = albumlib.get_album(album_id)
    album_is_public = True if (int(album["is_public"]) == 1) else False
    # Read all pictures in album
    (picture_cur, conn) = albumlib.get_album_pictures(album_id)

headers = {}
headers["Content-type"] = "text/html"
layoutlib.print_http_headers(headers)
layoutlib.print_page_open("PyGallery - Album")
print("<body>")
menu = []
menu.append(("Home", "gallery.cgi"))

session_user = None
if logged_in:
  session_user = usersession.get_session_user()

if album is None:
  layoutlib.print_page_header(menu, session_user)
  print('<div id="page_body">')
  print('<p>No album selected. Pick one <a href="gallery.cgi">here</a>.</p>')
  print('</div>')
else:
#  if user_authorized:
#    menu.append(("Add Picture", "album_picture_add.cgi?id=%d" % (album_id,)))
  layoutlib.print_page_header(menu, session_user)
  
  print('<div id="page_body">')
  if album_is_public or user_authorized:
    # Print header
    print('<h1>%s <span>by %s</span></h1>' % (album["name"], user["username"]))
    print('<p><a id="view_as_slideshow" href="slideshow.cgi?albumid=' + 
        str(album_id) + '">View as slideshow</a></p>')
    # Print command links for owner
    if user_authorized:
      # Tell them if this album is public or private
      # and a link to change the visibility
      print('<p>This album is')
      if album_is_public:
        print('public.</p>')
      else:
        print('private.</p>')
      print('<ul id="album_commands">')
      if album_is_public:
        print('<li id="album_vis"><a href="album.cgi?id=' + str(album_id) + 
            '&cmd=mkprivate">Make private</a></li>')
      else:
        print('<li id="album_vis"><a href="album.cgi?id=' + str(album_id) + 
            '&cmd=mkpublic">Make public</a></li>')
      print('<li id="album_delete"><a href="delete_album.cgi?id=' 
          + str(album_id) + '">Delete this album</a></li>') 
      print('<li id="album_recyclebin"><a href="album_recyclebin.cgi?id=' 
          + str(album_id) + '">Recycle Bin</a></li>')
      print('<li id="album_picture_add"><a href="album_picture_add.cgi?id='
          + str(album_id) + '">Add Picture</a></li>')
      print('</ul>')
    # Display images
    print('<ul id="album_container">')
    for picture in picture_cur:
      image_url = '/PictureShare/users/%s/%s/%s' % \
          (user["username"], "album"+str(album_id), picture["file_name"])
      image_thumb_url = '/PictureShare/users/%s/%s/%s' % \
          (user["username"], "albumthumb"+str(album_id), picture["file_name"])
      print('<li>')
      print('<a href="%s"><img height="100" src="%s" /></a>' % \
          (image_url, image_thumb_url))
      print('%s<br>' % picture["label"])
      if user_authorized:
        print('<a href="album.cgi?id=%d&cmd=delete&picid=%d">Delete</a>' % \
            (album_id, picture["picture_id"]))
      print('</li>')
    print('</ul>')
    picture_cur.close()
  elif (not int(album["is_public"]) == 1) and (not user_authorized):
    print("This is a private album.")
  print('</div>')
if conn:
  conn.close()
layoutlib.print_page_close()
